<template>
  <div class="bind-div">
    <!-- 扫码绑定  -->
    <van-row type="flex" justify="center" :style="{'margin-top':scanQrMarginTop,'margin-bottom':scanQrMarginBottom}">
      <van-col span="20">
        <sub-button btnText="扫一扫" @click.native="scannerQr"></sub-button>
      </van-col>
    </van-row>
    <!-- 手写绑定  -->
    <van-row type="flex" justify="center">
      <van-col span="20">
        <gray-button v-show="!handInputShow" btnText="手动输入" @click.native="handInput"></gray-button>

        <van-field
          v-model="macCode"
          center
          clearable
          label=""
          placeholder="输入设备编码"
          v-show="handInputShow"
        >
          <template #button>
            <van-button size="small" type="default" round
                        style="background-color: rgb(224, 224, 224);margin-right: 5px"
                        @click="handInput">取消
            </van-button>
            <van-button size="small" type="info" round @click="handInputCommit">添加</van-button>
          </template>
        </van-field>

      </van-col>
    </van-row>
    <!--    <van-dialog class="hand-input-bind-dialog"-->
    <!--                height="100%"-->
    <!--                v-model="handInputShow"-->
    <!--                :beforeClose="beforeClose"-->
    <!--                title="手动输入设备码"-->
    <!--                :show-cancel-button="true"-->
    <!--                :show-confirm-button="true"-->
    <!--                :close-on-click-overlay="true">-->
    <!--      <van-field-->
    <!--        v-model="macCode"-->
    <!--        placeholder="请输入设备码"-->
    <!--      />-->
    <!--    </van-dialog>-->
  </div>
</template>

<script>
  import SubButton from "@/components/SubButton";
  import GrayButton from "@/components/GrayButton";
  import {getUrlParamByUrl} from "@/util/GetUrlParam";
  import {Toast} from "vant";

  export default {
    name: "bind-comp",
    props: {
      scanQrMarginTop: {
        type: String,
        default: '10%'
      },
      scanQrMarginBottom: {
        type: String,
        default: '10%'
      }
    },
    data() {
      return {
        date: '',
        show: false,
        handInputShow: false,
        macCode: '',
      };
    },
    components: {
      SubButton,
      GrayButton,
    },
    methods: {
      formatDate(date) {
        return `${date.getMonth() + 1}/${date.getDate()}`;
      },
      onConfirm(date) {
        this.show = false;
        this.date = this.formatDate(date);
      },
      handInput() {
        let that = this;
        that.handInputShow = !that.handInputShow;
        that.macCode = '';
      },
      beforeClose(action, done) {
        let that = this;
        if (action === 'cancel') {
          done();
        } else if (action === 'confirm') {//确定按钮
          that.show = false;
          done();
          console.log('点击确认了')
          //判断是否配网
          that.checkSetNetwork()
        }
      },
      handInputCommit() {
        let that = this;
        if (!that.macCode) {
          Toast.fail('请输入设备号');
          return;
        }
        //恢复手动输入
        that.handInputShow = false;
        //通知父组件关闭弹窗
        that.notifyParentCloseBindCompDialog();
        //判断是否配网
        that.checkSetNetwork()
      },
      //扫码
      scannerQr() {
        let that = this;
        that.$wechat.scanQRCode({
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
          success: function (res) {
            setTimeout(() => {
              let result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
              //恢复手动输入
              that.handInputShow = false;
              //通知父组件关闭弹窗
              that.notifyParentCloseBindCompDialog();
              if ("scanQRCode:ok" === res.errMsg) {
                that.macCode = getUrlParamByUrl(result, 'deviceId');
                if (that.macCode) {
                  //确认是否配网
                  that.checkSetNetwork()
                } else {
                  alert('二维码内容错误：' + result)
                }
              } else {
                alert('扫码失败：' + res.errMsg)
              }
            }, 1000);
          },
          error: (res) => {
            alert('扫码错误')
            alert(res)
          }
        });
      },
      //确认配网情况
      checkSetNetwork() {
        let that = this;
        let param = {
          macAddress: that.macCode
        };
        that.$http.restPost('/checkBindDevices.do', param).then((res) => {
          //已经配网
          if (res.data && res.data.result === 1) {
            that.checkBind()
          }
          //未配网
          else {
            that.setNetWork()
          }
        })
      },
      //确认绑定情况
      checkBind() {
        let that = this;
        let cook = that.$cookies.get(process.env.VUE_APP_COOKIE_USER_KEY);
        let id = cook.userInfo.id;
        let param = {
          userId: id,
          userType: 2
        }
        that.$http.restPost('/findUserDeviceList.do', param).then((res) => {
          if (res.data.AppUserDevice && res.data.AppUserDevice.length > 0) {
            for (let i = 0; i < res.data.AppUserDevice.length; i++) {
              let deviceList = res.data.AppUserDevice[i];
              let deviceCode = deviceList.deviceCode;
              if (that.macCode === deviceCode) {
                alert('该设备已绑定')
                return;
              }
            }
            //未绑定，去绑定设备
            that.bindDevice()
          }
          //未绑定，去绑定设备
          else {
            that.bindDevice()
          }
        });
      },
      //绑定设备
      bindDevice() {
        let that = this;
        //获取地理位置
        that.$wechat.getLocation({
          type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90  lat纬度
            let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。 lng经

            let cook = that.$cookies.get(process.env.VUE_APP_COOKIE_USER_KEY);
            let id = cook.userInfo.id;
            let param = {
              userId: id,
              macAddress: that.macCode,
              phone: cook['userInfo']['phone'] ? cook['userInfo']['phone'] : '',
              lng: longitude,
              lat: latitude,
              address: 1,
              cityName: '北京',
              userType: 2
            };
            //绑定设备
            that.$http.restPost('/bindDevices.do', param).then(res => {
              console.log(res)
              alert('绑定成功');
              location.href = "main_v3.html?deviceId=" + that.macCode;
            });
          }
        });
      },
      //配网
      setNetWork() {
        let that = this;
        that.$wechat.checkJsApi({
          jsApiList: ['configWXDeviceWiFi', 'openWXDeviceLib', 'startScanWXDevice', 'onScanWXDeviceResult'],
          success: function (res) {
            console.log(res);
            that.$wechat.invoke('configWXDeviceWiFi', {}, function (res) {
              let err_msg = res.err_msg;
              if (err_msg == 'configWXDeviceWiFi:ok') {
                //配置成功
                alert("WIFI配置成功");
                //判断是否绑定过
                that.checkBind()
              } else {
                alert("配网失败");
              }
            });
          }
        });
      },
      //分享
      share() {
        let that = this;
        alert('分享');
        that.$wechat.ready(function () {


          //分享给个人
          that.$wechat.onMenuShareAppMessage({
            title: document.title, // 分享标题
            desc: '描述', // 分享描述
            link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: 'https://bodivis.oss-cn-beijing.aliyuncs.com/activityTest/079f3b30-f58c-4189-985a-7d7f6ea44a4f.jpeg', // 分享图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
              console.log("自定义分享成功")
            },
            cancel: function () {
              console.log("分享个人失败")
            }
          });


        });
      },
      //通知父组件
      notifyParentCloseBindCompDialog() {
        this.$emit('closeBindCompDialog', '')
      }
    },
  }
</script>
<style lang="css" scoped>
  /* ⬇ 绑定div ⬇ */
  .bind-div {

  }

  .bind-div > :first-child {

  }

  .bind-div > :last-child {
    margin-bottom: 10%;
  }

  /* ⬇ 扫一扫样式 ⬇ */
  .scan-qr-code-bind {
    width: 100%;
    height: 40px;
    border-radius: 40px;
  }

  /* ⬇ 手动输入样式 ⬇ */
  .hand-input-bind {
    width: 100%;
    height: 40px;
    border-radius: 40px;
  }

  .hand-input-bind-dialog {
    /*height: 100%;*/
  }

</style>
